<?php

class PartsController extends AController
{
	
	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('index', 'add','update', 'moveLeft', 'moveRight', 'admin','delete'),
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}
	
	public function actionIndex()
	{
		$model = new Part;
		
		$this->render('index', array(
			'model' => $model,
			'tree' => $this->loadPart(1)->getTree()
		));
	}
	
	public function actionMoveLeft(){
		$this->loadPart()->moveLeft();
		$this->redirect(array('index'));
	}

	public function actionMoveRight(){
		$this->loadPart()->moveRight();
		$this->redirect(array('index'));
	}
	
	public function actionAdd(){
		$node = $this->loadPart();

		$model = new Part;
		$model->parent_id = $node->id;
		if(isset($_POST['Part']))
		{
			$model->attributes=$_POST['Part'];
			if(isset($_POST['submitPart']) && $model->validate()) {
				$node->appendChild($model);
				$this->redirect(array('index'));
			}
		}
			
		$this->render('add', array(
			'model' => $model,
			'path' => array_reverse($node->getPath(), true)
		));
	}
	
	public function actionUpdate(){
		$model=$this->loadPart();
		if(isset($_POST['Part']))
		{
			$model->attributes=$_POST['Part'];
			if($model->save())
				$this->redirect(array('index'));
		}

		$this->render('update',array(
			'model'=>$model,
			'path' => array_reverse($model->getPath(), true)
		));
	}
	
	public function actionDelete(){
		$this->loadPart()->deleteNode();
		$this->redirect(array('index'));
	}
	
	protected function loadPart($id=null)
	{
		if($this->_model===null)
		{
			if($id!==null || isset($_GET['id']))
				$this->_model=Part::model()->findbyPk($id!==null ? $id : $_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}
}

?>